package com.emit.controller;

import cn.hutool.core.util.ObjectUtil;
import com.emit.exception.BizException;
import com.emit.form.UserForm;
import com.emit.security.MyUserDetailsServiceImpl;
import com.emit.service.UserService;
import com.emit.view.ResultView;
import com.emit.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

/**
 * 用户管理
 *
 * @author wanglongquan
 * @menu 用户管理
 */
@RestController
@RequestMapping("/user")
public class UserController {

  @Autowired private MyUserDetailsServiceImpl myUserDetailsService;

  @Autowired UserService userService;
  /**
   * 用户登录
   *
   * @param username 账号
   * @param password 密码
   * @return
   */
  @RequestMapping("/login")
  public ResultView<UserVO> login(
      @RequestParam("username") String username, @RequestParam("password") String password) {
    ResultView<UserVO> resultView = new ResultView<UserVO>();
    UserDetails userDetails = myUserDetailsService.loadUserByUsername(username);
    if (ObjectUtil.isNull(userDetails)) {
      throw new BizException("此账号不存在！");
    }
    if (!new BCryptPasswordEncoder().matches(password, userDetails.getPassword())) {
      throw new BizException("密码错误！");
    }
    UserVO userVO = userService.findUserByUsername(username);
    resultView.setData(userVO);
    return resultView;
  }

  /**
   * 用户注册
   *
   * @param userFrom
   * @return
   */
  @PostMapping(value = "/registered")
  public ResultView<UserVO> registered(@RequestBody UserForm userFrom) {
    ResultView<UserVO> resultView = new ResultView<UserVO>();
    resultView.setData(userService.registered(userFrom));
    return resultView;
  }
}
